package com.fuyin.commons.aspect;

import com.fuyin.commons.exception.ApiException;
import com.fuyin.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author yuanxilan (yuanxilan@keep.com)
 * @Description
 * @date 2021年10月27日 4:16 下午
 * @since
 */
@Aspect
@Component
@Slf4j
public class AuthAspect {

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Resource
    private RedisService redisService;

    @Before(value = "bean(userController) && args(token,..)", argNames = "token")
    public void authUser(String token) {
        token = StringUtils.substring(token, tokenHead.length());
        String role = redisService.get(token);
        log.info("com.fuyin.commons.aspect.AuthAspect.authUser role: {}", role);
        if (StringUtils.isBlank(role)) {
            throw new ApiException(401, "认证失效");
        }
        if (!"0".equals(role)) {
            throw new ApiException(403, "无权访问");
        }
    }

    @Before(value = "bean(adminController) && args(token,..)", argNames = "token")
    public void authAdmin(String token) {
        token = StringUtils.substring(token, tokenHead.length());
        String role = redisService.get(token);
        log.info("com.fuyin.commons.aspect.AuthAspect.authAdmin role: {}", role);
        if (StringUtils.isBlank(role)) {
            throw new ApiException(401, "认证失效");
        }
        if (!"1".equals(role)) {
            throw new ApiException(403, "无权访问");
        }
    }

    @Before(value = "bean(superAdminController) && args(token,..)", argNames = "token")
    public void authSuperAdmin(String token) {
        token = StringUtils.substring(token, tokenHead.length());
        String role = redisService.get(token);
        log.info("com.fuyin.commons.aspect.AuthAspect.authSuperAdmin role: {}", role);
        if (StringUtils.isBlank(role)) {
            throw new ApiException(401, "认证失效");
        }
        if (!"2".equals(role)) {
            throw new ApiException(403, "无权访问");
        }
    }
}
